package com.uziot.bucket.eureka.zuul.config;

import com.uziot.bucket.eureka.dao.GatewayApiDefineMapper;
import com.uziot.bucket.eureka.zuul.filter.ZuulAuthFilter;
import com.uziot.bucket.eureka.zuul.router.CustomRouteLocator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.Filter;

/**
 * @author shidt
 * @version V1.0
 * @className BasicRoute
 * @date 2020-12-16 23:48:56
 * @description Zuul网关配置，动态加载路由
 */
@Configuration
public class ZuulConfig {
    @Autowired
    private ZuulProperties zuulProperties;
    @Autowired
    private ServerProperties server;
    @Autowired
    private GatewayApiDefineMapper gatewayApiDefineMapper;


    @Bean
    public ZuulAuthFilter preFilter() {
        return new ZuulAuthFilter();
    }

    /**
     * 跨域过滤器
     *
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean<?> corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(18000L);
        source.registerCorsConfiguration("/**", config);
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(corsFilter);
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }

    /**
     * 动态路由
     *
     * @return PropertiesRouter
     * <p>
     * PropertiesRouter
     */
    @Bean
    public CustomRouteLocator routeLocator() {
        ServerProperties.Servlet servlet = this.server.getServlet();
        String contextPath = servlet.getContextPath();
        CustomRouteLocator routeLocator = new CustomRouteLocator(contextPath, this.zuulProperties);
        routeLocator.setGatewayApiDefineMapper(gatewayApiDefineMapper);
        return routeLocator;
    }

}
